package com.model;

import com.employee.controller.ContactBeanRemote;
import com.controller.bean.Login;
import java.io.IOException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class MailService
{
    private static MailService theService = null;
    private static Session mailSession;
    
    private static final String HOST = "smtp.gmail.com";
    private static final int PORT = 465;
    private static final String USER = "anhntv_b01499@fpt.aptech.ac.vn";
    private static final String PASSWORD = "chankochiudc";
    private static String FROM = "";

    public MailService()
    {
        Properties props = new Properties();
        
        props.put("mail.transport.protocol", "smtps");
        props.put("mail.smtps.host", HOST);
        props.put("mail.smtps.auth", "true");
        props.put("mail.smtp.from", FROM);
        props.put("mail.smtps.quitwait", "false");

        mailSession = Session.getDefaultInstance(props);
        mailSession.setDebug(true);
    }
        
    public static void sendEmail(String sender, String recipent, String subject, String message) throws AddressException, MessagingException{
       
            if(theService == null){
                theService = new MailService();
            }
            FROM = sender;
            MimeMessage mimeMessage = new MimeMessage(mailSession);
            mimeMessage.setFrom(new InternetAddress(FROM));
            mimeMessage.setSender(new InternetAddress(FROM));
            mimeMessage.setSubject(subject);
            mimeMessage.setContent(message,"text/plain");
            
            mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(recipent));
            
            Transport transport = mailSession.getTransport("smtps");
            transport.connect(HOST, PORT, USER, PASSWORD);
            transport.sendMessage(mimeMessage, mimeMessage.getRecipients(Message.RecipientType.TO));
            
            transport.close();
    }
    
    public static void sendContact(String username,String message){
        try
        {
            InitialContext ic = new InitialContext();
            ContactBeanRemote remote = (ContactBeanRemote) ic.lookup("java:global/BluePumpkinEJB/ContactBean!com.employee.controller.ContactBeanRemote");
            remote.send(username, message);
        } catch (NamingException ex)
        {
            Logger.getLogger(MailService.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
